package com.lk.client.rpc;

import com.lk.client.discovery.SeviceDiscovery;
import com.lk.client.rpc.handler.InitializerHandler;
import com.lk.entity.Service;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.Data;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author kun.li
 */
@Data
public class RpcClient {

    public static Map<String, Channel> channels = new ConcurrentHashMap<>();

    public static volatile RpcClient rpcClient = new RpcClient();

    public static RpcClient getInstance() {
        return rpcClient;
    }

    public Channel start() {
        Service service = SeviceDiscovery.getService("netty-server");
        if (channels.get(service.getServiceName()) != null) {
            return channels.get(service.getServiceName());
        }
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            ChannelFuture channelFuture = bootstrap
                    .group(nioEventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new InitializerHandler())
                    .connect(service.getIp(), service.getPort());
            Channel channel = channelFuture.sync().channel();
            channel.closeFuture().addListener((ChannelFutureListener) channelFuture1 -> {
                nioEventLoopGroup.shutdownGracefully();
            });
            channels.put(service.getServiceName(), channel);
            return channel;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
